package top.hzy520.reattend.service;

import lombok.extern.slf4j.Slf4j;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.engine.*;
import org.activiti.engine.history.HistoricActivityInstance;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.impl.cfg.ProcessEngineConfigurationImpl;
import org.activiti.engine.impl.context.Context;
import org.activiti.engine.impl.persistence.entity.ProcessDefinitionEntity;
import org.activiti.engine.impl.pvm.PvmTransition;
import org.activiti.engine.impl.pvm.process.ActivityImpl;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.activiti.image.ProcessDiagramGenerator;
import org.activiti.spring.ProcessEngineFactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import top.hzy520.attend.dao.AttendItemMapper;
import top.hzy520.attend.entity.AttendItem;
import top.hzy520.reattend.dao.ReAttendMapper;
import top.hzy520.reattend.entity.ReAttend;
import top.hzy520.role.dao.RoleMapper;
import top.hzy520.user.entity.User;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

/**
 * @Author: HouZeYu
 * @Description:
 * @Date: Created in 11:11 2018/8/8
 */
@Slf4j
@Service
public class ReattendServiceImpl implements ReattendService {

    private static final String RE_ATTEND_FLOW_ID = "re_attend";

    /**
     * 补签流程状态
     */
    private static final Byte RE_ATTEND_STATUS_ONGOING =1 ;
    private static final Byte RE_ATTEND_STATUS_PSSS =2 ;
    private static final Byte RE_ATTEND_STATUS_REFUSE =3 ;
    /**
     *
     */
    private static final Byte ATTEND_STATUS_NORMAL =1 ;
    /**
     * 流程下一步处理人
     */
    private static final String NEXT_HANDLER = "next_handler";
    /**
     * 任务关联补签数据键
     */
    private static final String RE_ATTEND_SIGN = "re_attend";
    @Autowired
    private HistoryService historyService;
    @Autowired
    RepositoryService repositoryService;
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private TaskService taskService;
    @Autowired
    private ReAttendMapper reAttendMapper;
    @Autowired
    private AttendItemMapper attendItemMapper;
    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    ProcessEngineConfiguration processEngineConfiguration;
    @Autowired
    ProcessEngineFactoryBean processEngine;

    @Override
    public void startReattendFlow(ReAttend reAttend, User user) throws IOException {
         //向补签数据表插入数据
         reAttend.setCurrentHandler("houzeyu");  //设置下一个流程处理人
         reAttend.setStatus(RE_ATTEND_STATUS_ONGOING);
         reAttend.setAttendDate(new Date());
       reAttendMapper.insertSelective(reAttend);
          Map<String,Object> map=new HashMap<>();
          map.put(RE_ATTEND_SIGN,reAttend);
          List<String> userList=new ArrayList<>();
          userList.add(reAttend.getCurrentHandler());
          userList.add("houzeyu1");
          map.put("userList",userList);
          //启动补签工作流
          ProcessInstance instance = runtimeService.startProcessInstanceByKey(RE_ATTEND_FLOW_ID,map);
          //提交用户补签任务
         Task task = taskService.createTaskQuery().processInstanceId(instance.getId()).singleResult();
         taskService.complete(task.getId(),map);
        System.out.println(task.getProcessInstanceId());
    }
    @Override
    public List<ReAttend> reAttendList(String username) {
        List<ReAttend> reAttendList = new ArrayList<ReAttend>();
        List<Task> taskList= taskService.createTaskQuery().taskCandidateOrAssigned(username).list();
        taskList.stream().forEach(param->{
            //取出流程变量
            Map<String, Object> variable = taskService.getVariables(param.getId());
            //取出变量
            ReAttend reAttend = (ReAttend)variable.get(RE_ATTEND_SIGN);
            reAttend.setTaskId(param.getId());
            reAttendList.add(reAttend);
        });
        return reAttendList;
    }
    @Override
    public void approveReattendFlow(ReAttend reAttend) {
        Map<String,Object> variable=taskService.getVariables(reAttend.getTaskId());
        ReAttend mapReAttend = (ReAttend)variable.get(RE_ATTEND_SIGN);
        //如果审批通过修改补签数据状态和考勤数据状态
        if ((""+RE_ATTEND_STATUS_PSSS).equals(reAttend.getApproveFlag())){
            AttendItem attendItem=new AttendItem();
            attendItem.setId(mapReAttend.getAttendId());
            attendItem.setAttendStatus(ATTEND_STATUS_NORMAL);
            attendItemMapper.updateByPrimaryKeySelective(attendItem);
            mapReAttend.setStatus(RE_ATTEND_STATUS_PSSS);
            reAttendMapper.updateByPrimaryKeySelective(mapReAttend);
        }else {
            //没有通过则修改补签数据表状态
            mapReAttend.setStatus(RE_ATTEND_STATUS_REFUSE);
            reAttendMapper.updateByPrimaryKeySelective(mapReAttend);
        }
        taskService.complete(reAttend.getTaskId());
    }

    @Override
    public List<ReAttend> myreattend(User user) {
        return reAttendMapper.selectReattendByRealName(user.getRealName());
    }

    /***
     *生成执行流程图
     * @param processInstanceId
     * @param response 流程图图片
     * @throws IOException
     */
   @Override
    public void  draw(String processInstanceId,HttpServletResponse response) throws IOException {

        //获取历史流程实例
        HistoricProcessInstance processInstance =  historyService.createHistoricProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
        //获取流程图
        BpmnModel bpmnModel = repositoryService.getBpmnModel(processInstance.getProcessDefinitionId());
        processEngineConfiguration = processEngine.getProcessEngineConfiguration();
        Context.setProcessEngineConfiguration((ProcessEngineConfigurationImpl) processEngineConfiguration);

        ProcessDiagramGenerator diagramGenerator = processEngineConfiguration.getProcessDiagramGenerator();
        ProcessDefinitionEntity definitionEntity = (ProcessDefinitionEntity)repositoryService.getProcessDefinition(processInstance.getProcessDefinitionId());

        List<HistoricActivityInstance> highLightedActivitList =  historyService.createHistoricActivityInstanceQuery().processInstanceId(processInstanceId).list();
        //高亮环节id集合
        List<String> highLightedActivitis = new ArrayList<String>();
        //高亮线路id集合
        List<String> highLightedFlows = getHighLightedFlows(definitionEntity,highLightedActivitList);

        for(HistoricActivityInstance tempActivity : highLightedActivitList){
            String activityId = tempActivity.getActivityId();
            highLightedActivitis.add(activityId);
        }

        //中文显示的是口口口，设置字体就好了bpmnModel, imageType, highLightedActivities, highLightedFlows,null, null, null,null, scaleFactor
        InputStream imageStream = diagramGenerator.generateDiagram(bpmnModel, "png", highLightedActivitis,highLightedFlows,"宋体","宋体",null,null,1.0);
        //单独返回流程图，不高亮显示
//        InputStream imageStream = diagramGenerator.generatePngDiagram(bpmnModel);
        // 输出资源内容到相应对象
        byte[] b = new byte[1024];
        int len;
        while ((len = imageStream.read(b, 0, 1024)) != -1) {
            response.getOutputStream().write(b, 0, len);
        }
    }

    /**
     * 生成高亮连线
     * @param processDefinitionEntity
     * @param historicActivityInstances
     * @return
     */
    private List<String> getHighLightedFlows(
            ProcessDefinitionEntity processDefinitionEntity,
            List<HistoricActivityInstance> historicActivityInstances) {
        List<String> highFlows = new ArrayList<String>();// 用以保存高亮的线flowId
        for (int i = 0; i < historicActivityInstances.size() - 1; i++) {// 对历史流程节点进行遍历
            ActivityImpl activityImpl = processDefinitionEntity
                    .findActivity(historicActivityInstances.get(i)
                            .getActivityId());// 得到节点定义的详细信息
            List<ActivityImpl> sameStartTimeNodes = new ArrayList<ActivityImpl>();// 用以保存后需开始时间相同的节点
            ActivityImpl sameActivityImpl1 = processDefinitionEntity
                    .findActivity(historicActivityInstances.get(i + 1)
                            .getActivityId());
            // 将后面第一个节点放在时间相同节点的集合里
            sameStartTimeNodes.add(sameActivityImpl1);
            for (int j = i + 1; j < historicActivityInstances.size() - 1; j++) {
                HistoricActivityInstance activityImpl1 = historicActivityInstances
                        .get(j);// 后续第一个节点
                HistoricActivityInstance activityImpl2 = historicActivityInstances
                        .get(j + 1);// 后续第二个节点
                if (activityImpl1.getStartTime().equals(
                        activityImpl2.getStartTime())) {
                    // 如果第一个节点和第二个节点开始时间相同保存
                    ActivityImpl sameActivityImpl2 = processDefinitionEntity
                            .findActivity(activityImpl2.getActivityId());
                    sameStartTimeNodes.add(sameActivityImpl2);
                } else {
                    // 有不相同跳出循环
                    break;
                }
            }
            List<PvmTransition> pvmTransitions = activityImpl
                    .getOutgoingTransitions();// 取出节点的所有出去的线
            for (PvmTransition pvmTransition : pvmTransitions) {
                // 对所有的线进行遍历
                ActivityImpl pvmActivityImpl = (ActivityImpl) pvmTransition
                        .getDestination();
                // 如果取出的线的目标节点存在时间相同的节点里，保存该线的id，进行高亮显示
                if (sameStartTimeNodes.contains(pvmActivityImpl)) {
                    highFlows.add(pvmTransition.getId());
                }
            }
        }
        return highFlows;
    }
}
